
cmake_minimum_required(VERSION 3.12.0)

project(Ascend_C)

set(CMAKE_CXX_STANDARD 17)

set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type Release/Debug (default Debug)" FORCE)
set(CMAKE_INSTALL_PREFIX "${CMAKE_CURRENT_LIST_DIR}/out" CACHE STRING "path for install()" FORCE)

if(EXISTS /home/ma-user/Ascend/ascend-toolkit/latest)
  set(ASCEND_CANN_PACKAGE_PATH "/home/ma-user/Ascend/ascend-toolkit/latest")
elseif(EXISTS /usr/local/Ascend/ascend-toolkit/latest)
  set(ASCEND_CANN_PACKAGE_PATH "/usr/local/Ascend/ascend-toolkit/latest")
elseif(EXISTS /media/aaa/data/softs/Ascend/ascend-toolkit/latest)
  set(ASCEND_CANN_PACKAGE_PATH "/media/aaa/data/softs/Ascend/ascend-toolkit/latest")
endif()


message("CMAKE_CURRENT_SOURCE_DIR is ${CMAKE_CURRENT_SOURCE_DIR}")

add_library(torch_utils SHARED ${CMAKE_CURRENT_SOURCE_DIR}/torch_utils.cpp)
target_link_libraries(torch_utils PRIVATE
    torch_npu
)
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
execute_process(COMMAND python3 -c "from importlib.metadata import distribution;dist = distribution('torch').locate_file('');print(f'{dist}/torch')"
  OUTPUT_STRIP_TRAILING_WHITESPACE
  OUTPUT_VARIABLE TORCH_PATH
)
message("TORCH_PATH is ${TORCH_PATH}")
execute_process(COMMAND python3 -c "from importlib.metadata import distribution;dist = distribution('torch_npu').locate_file('');print(f'{dist}/torch_npu')"
  OUTPUT_STRIP_TRAILING_WHITESPACE
  OUTPUT_VARIABLE TORCH_NPU_PATH
)
message("TORCH_NPU_PATH is ${TORCH_NPU_PATH}")
target_link_directories(torch_utils PRIVATE
  ${TORCH_PATH}/lib
  ${TORCH_NPU_PATH}/lib
  ${ASCEND_CANN_PACKAGE_PATH}/lib64/
)
message("${ASCEND_CANN_PACKAGE_PATH}/include")
target_include_directories(torch_utils PRIVATE
  ${CMAKE_CURRENT_SOURCE_DIR}
  ${ASCEND_CANN_PACKAGE_PATH}/include
  ${TORCH_NPU_PATH}/include
  ${TORCH_PATH}/include
  ${TORCH_PATH}/include/torch/csrc/api/include
)
target_link_libraries(torch_utils PRIVATE
  ${ASCEND_CANN_PACKAGE_PATH}/lib64/libascendcl.so
  ${ASCEND_CANN_PACKAGE_PATH}/lib64/libacl_op_compiler.so
  ${ASCEND_CANN_PACKAGE_PATH}/lib64/libnnopbase.so
  stdc++
)

execute_process(COMMAND python3 -m pybind11 --includes
  OUTPUT_STRIP_TRAILING_WHITESPACE
  OUTPUT_VARIABLE PYBIND11_INC
)
string(REPLACE " " ";" PYBIND11_INC ${PYBIND11_INC})
message("PYBIND11_INC: ${PYBIND11_INC}")
target_compile_options(torch_utils PRIVATE
  ${PYBIND11_INC}
#  -D_GLIBCXX_USE_CXX11_ABI=0
#  -O2
#  -std=c++17
)
execute_process(COMMAND python3-config --extension-suffix
  OUTPUT_STRIP_TRAILING_WHITESPACE
  OUTPUT_VARIABLE PYBIND11_SUFFIX
)

message("PYBIND11_SUFFIX:${PYBIND11_SUFFIX}")
set_target_properties(torch_utils PROPERTIES
  OUTPUT_NAME ascend_ops${PYBIND11_SUFFIX}
  PREFIX "" SUFFIX ""
)

